<template>
  <div class="container">
    <h1>购物平台后台管理系统</h1>
    <div class="box">
      <div class="left" />
      <div class="right">
        <h4>登 录</h4>
        <!-- 表单 -->
        <div class="form_box">
          <el-form
            ref="loginFormRef"
            class="form"
            :model="loginForm"
            :rules="rules"
            autocomplete="on"
            label-position="left"
          >
            <!-- <div style="text-align:center;height:60px;line-height:60px;font-weight:bold">用户名密码登录</div> -->
            <el-form-item prop="username" label="用户名:" label-width="70px" style="margin-bottom:3em">
              <el-input
                ref="username"
                v-model="loginForm.username"
                class="input"
                placeholder="请输入用户名"
                type="text"
              />
            </el-form-item>
            <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
              <el-form-item prop="password" label="密码:" label-width="70px">
                <el-input
                  :key="passwordType"
                  ref="password"
                  v-model="loginForm.password"
                  class="input"
                  :type="passwordType"
                  placeholder="请输入密码"
                  show-password
                />
              </el-form-item>
            </el-tooltip>
            <div class="inputYzm vfCode" v-if="isSidentify >= 3">
              <input placeholder="请输入验证码" v-model="sidentifyMode" />
              <div @click="refreshCode()" class="vfCodeComponents" title="点击切换验证码">
                <SIdentify :identifyCode="identifyCode"></SIdentify>
              </div>
            </div>
            <div>
              <input class="submit1 submit" type="button" value="登录" @click="login" />
              <input class="submit2 submit" type="button" value="重置" @click="resetLoginForm" />
            </div>
          </el-form>
          <!-- 表单 -->
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import SIdentify from './SIdentify.vue'
export default {
  components: { SIdentify },
  name: 'Login',
  data() {
    // const validateUsername = (rule, value, callback) => {
    //   callback()
    // }
    // const validatePassword = (rule, value, callback) => {
    //   callback()
    // }
    return {
      visible: false,
      form: {},
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ]
      },
      loginForm: {
        username: '',
        password: ''
      },
      // loginRules: {
      //   username: [
      //     { required: true, trigger: 'blur', validator: validateUsername }
      //   ],
      //   password: [
      //     { required: true, trigger: 'blur', validator: validatePassword }
      //   ]
      // },
      passwordType: 'password',
      capsTooltip: false,
      redirect: undefined,
      otherQuery: {},
      isSidentify: 3,
      sidentifyMode: '',
      identifyCode: '',
      identifyCodes: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']//验证码出现的数字和字母
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query
        if (query) {
          console.log(query);
          // this.redirect = query.redirect
          // this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
    this.$nextTick(() => {
      this.loginForm.username = 'admin'
      this.loginForm.password = '123456'
    })
    this.refreshCode()
  },
  created() {
  },
  methods: {
    // 表单重置按钮
    resetLoginForm() {
      // console.log(this)
      // resetFields：element-ui提供的表单方法
      // this.refs["loginForm"].resetFields()
      this.$refs.loginFormRef.resetFields()
      console.log(this.$refs.loginFormRef);
    },
    login() {
      // 表单预验证
      // valid：bool类型
      this.$refs.loginFormRef.validate(async valid => {
        if (!this.sidentifyMode) {
          this.$message({
            type: 'warning',
            duration: '2000',
            message: '验证码不能为空！'
          })
          return
        }
        if (this.sidentifyMode.toLowerCase() != this.identifyCode.toLowerCase()) {
          this.$message({
            type: 'warning',
            duration: '2000',
            message: '验证码错误！'
          })
          this.refreshCode()
          return
        }
        else {
          // console.log(valid)
          if (!valid) return false
          // this.$http.post('login', this.loginForm): 返回值为promise
          // 返回值为promise，可加await简化操作 相应的也要加async
          const { data: res } = await this.$http.post('login', this.loginForm)
          // console.log(res)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success('登录成功')
          // 1、将登陆成功之后的token, 保存到客户端的sessionStorage中; localStorage中是持久化的保存
          //   1.1 项目中出现了登录之外的其他API接口，必须在登陆之后才能访问
          //   1.2 token 只应在当前网站打开期间生效，所以将token保存在sessionStorage中
          window.sessionStorage.setItem('token', res.data.token)
          // 2、通过编程式导航跳转到后台主页, 路由地址为：/home
          this.$router.push('/home')
        }
      })
    },
    // 生成随机数
    randomNum(min, max) {
      max = max + 1
      return Math.floor(Math.random() * (max - min) + min)
    },
    // 更新验证码
    refreshCode() {
      this.identifyCode = ''
      this.makeCode(this.identifyCodes, 4)
      // console.log('当前验证码:', this.identifyCode)
    },
    // 随机生成验证码字符串
    makeCode(data, len) {
      // console.log('data, len:', data, len)
      for (let i = 0; i < len; i++) {
        this.identifyCode += this.identifyCodes[this.randomNum(0, this.identifyCodes.length - 1)]
      }
    },
  }
}
</script>

<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
  font-size: 0.7rem;
  width: 100%;
  height: 100%;
  position: fixed;
  background: linear-gradient(120deg, #e0c3fc 0%, #8ec5fc 100%) no-repeat;
}
h1 {
  font-size: 4rem;
  text-align: center;
  margin-top: 3rem;
  text-shadow: 5px 5px 5px #ccc;
  color: #fff;
}
::selection {
  color: #fff;
  background-color: rgb(144, 129, 241);
}

.box {
  display: flex;
  overflow: hidden;
  width: 60rem;
  height: 32rem;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 1.5rem;
  margin: 4rem auto;
  box-shadow: 0 0 1rem 0.2rem rgba(0, 0, 0, 0.1);
}

.box .left {
  position: relative;
  width: 40%;
  height: 100%;
  background-color: skyblue;
}

.box .left::before {
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
  background-image: url('./left1.png');
  background-size: 100% 100%;
  opacity: 0.8;
}

.box .right {
  // display: flex;
  width: 65%;
  // flex-direction: column;
  // align-items: center;
}

.box .right h4 {
  text-align: center;
  color: rgb(144, 129, 241);
  font-size: 2.8rem;
  margin-top: 4.5rem;
}

.box .right .form_box .form {
  // display: flex;
  // flex-direction: column;
  // align-items: stretch;
  width: 60%;
  margin-left: 10em;
  padding-top: 4em;
}
.box .right .form_box .form .password {
  padding-top: 2em;
}

.right .submit1 {
  display: inline-block;
  position: relative;
  width: 7rem;
  height: 3rem;
  color: #f6f6f6;
  background-image: linear-gradient(120deg, #e0c3fc 0%, #8ec5fc 100%);
  font-size: 1.2rem;
  border: none;
  border-radius: 0.5rem;
  margin: 3rem 0 0 4rem;
  transform: translateX(-40%);
}
.right .submit2 {
  display: inline-block;
  position: relative;
  width: 7rem;
  height: 3rem;
  color: #f6f6f6;
  background-image: linear-gradient(120deg, #e0c3fc 0%, #8ec5fc 100%);
  font-size: 1.2rem;
  border: none;
  border-radius: 0.5rem;
  margin: 3rem 0 0 4rem;
  transform: translateX(-10%);
}

.right .submit:hover {
  box-shadow: 0 0 2rem -0.5rem rgba(0, 0, 0, 0.15);
  cursor: pointer;
}
.vfCode {
  background: #fff;
  width: 140px;
  height: 50px;
  border-radius: 25px;
  border: solid 1px #13c2c0;
  margin-top: 38px;
  margin-left: 70px;
  &.inputYzm {
    background: white;
    background-size: 35px 35px;
  }
  input {
    background: none;
    border: none;
    outline: none;
    width: 100px;
    height: 100%;
    margin-left: 20px;
    font-size: 16px;
    border-radius: 0px 35px 35px 0px;
    box-shadow: inset 0 0 0 1000px #fff !important;
  }
  .vfCodeComponents {
    position: relative;
    bottom: 43px;
    left: 173px;
    cursor: pointer;
  }
}
</style>
